// 导入外部模块
const { customRequire } = require('./utils.js');
let axios = customRequire('axios');
const https = require('https');

// 验证axios是否正确加载，如果不是，尝试直接导入
if (!axios || typeof axios.post !== 'function') {
    console.log('通过customRequire加载的axios无效或不包含post方法，尝试直接导入');
    try {
        axios = require('axios');
    } catch (err) {
        console.error('直接导入axios也失败:', err.message);
    }
}

const url = 'https://api.powerbi.com/beta/e96fa72b-c8d6-4957-96bd-c7f8dc30cc88/datasets/31fb02b8-3e95-4bec-b9b2-5af9c0d67aa0/rows?experience=power-bi&key=28Ri5RxnC5wvZFax5umuUDI2FZi6LxZ6q1bZPLqtfNfSXkLIuxqvge6bkETamwjdYIo%2F0EP8sgoAVzi55wI2Dw%3D%3D';

// 使用Node.js内置https模块发送请求的备用方法
async function sendWithNodeHttps(data) {
    return new Promise((resolve, reject) => {
        const options = {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            rejectUnauthorized: false // 忽略HTTPS证书验证
        };

        const req = https.request(url, options, (res) => {
            let responseData = '';
            res.on('data', (chunk) => {
                responseData += chunk;
            });
            res.on('end', () => {
                console.log('status code：', res.statusCode);
                console.log('respose data：', responseData);
                resolve({
                    status: res.statusCode,
                    data: responseData
                });
            });
        });

        req.on('error', (error) => {
            reject(error);
        });

        req.write(JSON.stringify(data));
        req.end();
    });
}

async function sendMonitoringData(data) {
    try {
        console.log('sending pbi data:', data);
        
        // 再次检查axios是否有效
        if (axios && typeof axios.post === 'function') {
            // 使用axios发送请求
            const agent = new https.Agent({ rejectUnauthorized: false });
            const response = await axios.post(url, data, { httpsAgent: agent });
            console.log('status code：', response.status);
            console.log('respose data：', response.data);
            return { success: true, message: '监控数据发送成功' };
        } else {
            // 使用备用方法发送请求
            console.log('axios无效，使用Node.js内置https模块发送请求');
            const response = await sendWithNodeHttps(data);
            return { success: true, message: '监控数据发送成功(使用备用方法)' };
        }
    } catch (error) {
        console.error('Error sending monitoring data:', error.message);
        let errorMessage = '';
        if (error.response) {
            errorMessage = `服务器响应错误: ${error.response.status} ${JSON.stringify(error.response.data)}`;
            console.error('Response status:', error.response.status);
            console.error('Response data:', error.response.data);
        } else if (error.request) {
            errorMessage = '未收到服务器响应，可能是网络问题或服务器不可用';
            console.error('No response received:', error.request);
        } else {
            errorMessage = `请求设置错误: ${error.message}`;
            console.error('Error setting up the request:', error.message);
        }
        return { success: false, message: errorMessage };
    }
}

module.exports = {
    sendMonitoringData
};
